package com.ztw.yygh.order.controller;

import com.ztw.yygh.common.exception.YyghException;
import com.ztw.yygh.common.result.Result;
import com.ztw.yygh.order.service.PaymentService;
import com.ztw.yygh.order.service.WeiXinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/order/weixin")
public class WeiXinController {


    @Autowired
    private WeiXinService weiXinService;

    @Autowired
    private PaymentService paymentService;
    //生成二维码
    @GetMapping("/createNative/{orderId}")
    public Result createNative(@PathVariable Long orderId) {
        Map map=new HashMap<>();
        try {
            map = weiXinService.createNative(orderId);
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.ok(map);
    }
    //查看支付状态
    @GetMapping("queryPayStatus/{orderId}")
    public Result queryPayStatus(@PathVariable Long orderId){
        //调用微信接口查看支付状态
        Map<String,String> resultMap=weiXinService.queryPayStatus(orderId);
        //支付状态判断
        if(resultMap==null){
            return Result.fail().message("支付出错");
        }
        if("SUCCESS".equals(resultMap.get("trade_state"))){
            //更新订单状态
            String outTradeNo = resultMap.get("out_trade_no");//订单编码
            paymentService.paySuccess(outTradeNo,resultMap);
            return Result.ok().message("支付成功");
        }
        return Result.ok().message("支付中");
    }
}
